package be.myandroid.games;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

import be.myandroid.games.menu.AbstractMenu;
import be.myandroid.games.menu.MenuMaker;
import be.myandroid.games.menu.PauseMenu;
import be.myandroid.games.menu.ProxyMenu;

import android.content.Context;
import android.opengl.GLSurfaceView;
import android.opengl.GLU;


public class HelloOpenGLES10Renderer implements GLSurfaceView.Renderer{

	public float mAngle;
	private Context context;
	public Game game;
	public MenuMaker menuMaker;

	public HelloOpenGLES10Renderer(Context context){
		this.context = context;
	}

	public void onSurfaceCreated(GL10 gl, EGLConfig config) {
		// Set the background frame color
		gl.glClearColor(0.0f, 0.0f, 0.0f, 1.0f);

		if(game == null)
			game = new Game();
		
		AbstractMenu menu = new ProxyMenu(context);
		menuMaker = MenuMaker.getInstance(gl,context,menu);
	}

	public void onDrawFrame(GL10 gl) {
		// Redraw background color
		gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);

		// Set GL_MODELVIEW transformation mode
		gl.glMatrixMode(GL10.GL_MODELVIEW);
		gl.glLoadIdentity();   // reset the matrix to its default state

		// When using GL_MODELVIEW, you must set the view point
		GLU.gluLookAt(gl, 0, 0, -5, 0f, 0f, 0f, 0f, 1.0f, 0.0f);

		// Create a rotation for the triangle (Boring! Comment this out:)
		// long time = SystemClock.uptimeMillis() % 4000L;
		// float angle = 0.090f * ((int) time);

		// Use the mAngle member as the rotation value
		gl.glRotatef(mAngle, 0.0f, 0.0f, 1.0f); 
		gl.glEnable (GL10.GL_BLEND);
		gl.glBlendFunc (GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);

		game.draw(gl);
		menuMaker.draw(gl);
	}

	public void onSurfaceChanged(GL10 gl, int width, int height) {
		gl.glViewport(0, 0, width, height);
		menuMaker.OnSurfaceChanged(gl,width,height);
		// make adjustments for screen ratio
		float ratio = (float) width / height;
		gl.glMatrixMode(GL10.GL_PROJECTION);        // set matrix to projection mode
		gl.glLoadIdentity();                        // reset the matrix to its default state
		gl.glFrustumf(-ratio, ratio, -1, 1, 3, 7);  // apply the projection matrix

		/*
		 * Set our projection matrix. This doesn't have to be done
		 * each time we draw, but usually a new projection needs to
		 * be set when the viewport is resized.
		 */

		menuMaker.getCurrentProjection(gl);
	}
}
